package com.lln.cjcx.service.impl;
import com.lln.cjcx.pojo.Message;
import com.lln.cjcx.pojo.MyOkHttpClient;
import com.lln.cjcx.service.LoginService;
import com.lln.cjcx.util.CommonUtils;
import com.lln.cjcx.value.UrlValue;
import org.jetbrains.annotations.Nullable;
import kotlin.jvm.internal.Intrinsics;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
 * @author LiLinnan
 * @version 1.0
 * @date 2020/1/14 20:27
 */
@Service public final class LoginServiceImpl extends LoginService {
	public LoginServiceImpl(){
		super();
	}
	@Override
	public final String getServName() {
		return "登录服务";
	}

	private final static String MAIN_INDEX_NAME = "index.jsp";
	private final static String INVALID_SESSION = "invalidSession";
	private final static String BAD_CAPTCHA = "badCaptcha";
	private final static String BAD_CREDENTIALS = "badCredentials";
	@Override public final Message login(@NotNull MyOkHttpClient myOkHttpClient, @Nullable String studentNumber,@Nullable String password,@Nullable String captcha) {
		Intrinsics.checkParameterIsNotNull(myOkHttpClient,"myOkhttpClient");
		if (studentNumber == null || password == null || captcha == null) {
			return new Message(-1, "请将信息填写完整");
		}
		OkHttpClient client = myOkHttpClient.client;
		FormBody form = new FormBody.Builder()
				.add("j_username", studentNumber)
				.add("j_password", CommonUtils.md5(password))
				.add("j_captcha", captcha)
				.build();
		Request loginRequest = new Request.Builder().url(UrlValue.loginUrl(myOkHttpClient.port))
				.post(form).build();
		Response response;
		try {
			Exception ex = null;
			response = client.newCall(loginRequest).execute();
			try{
				Intrinsics.checkNotNull(response,"response returns a null");
				Intrinsics.checkNotNull(response.request(),"response.request() returns null");
				Intrinsics.checkNotNull(response.request().url(),"response.request().url() returns null");
				Intrinsics.checkNotNull(response.request().url().toString(),"response.request().url().toString() returns null");
			}catch (NullPointerException npe){
				throw new Exception(npe);
			}
			String url = response.request().url().toString();
			if (url.endsWith(MAIN_INDEX_NAME)) {
				//登录成功
				okhttp3.ResponseBody body=response.body();
				Intrinsics.checkNotNull(body,"response returns a null body");
				String name = getName(Objects.requireNonNull(response.body()).string());
				myOkHttpClient.student.setName(name);
				myOkHttpClient.student.setNumber(studentNumber);
				myOkHttpClient.setLogin(true);
				response.close();
				return new Message(1, "登录成功");
			}
			String begin = "errorCode=";
			int i = url.indexOf(begin);
			Message reason;
			if (i == -1) {
				reason = new Message(-1, "登录失败，未知原因");
			} else {
				reason = getReason(url.substring(i + begin.length()));
			}
			return reason;
		} catch (Throwable e) {
			e.printStackTrace(System.out);
			//登录失败了，进行端口号切换
			myOkHttpClient.changePort();
			return new Message(-1, e.getMessage());
		}
	}
	@NotNull private static Message getReason(@Nullable String code) {
		Message msg = new Message();
		msg.status = -1;
		if (INVALID_SESSION.equals(code)) {
			msg.data = "验证码超时";
		} else if (BAD_CAPTCHA.equals(code)) {
			msg.data = "验证码有误";
		} else if (BAD_CREDENTIALS.equals(code)) {
			msg.data = "密码错误";
		} else {
			msg.data = ((code == null) ? "" : code);
		}
		return msg;
	}
	private static String getName(String html) {
		String begin = "<small>欢迎您，</small>";
		int a = html.indexOf(begin);
		String end = "</span>";
		int b = html.indexOf(end, a);
		return html.substring(a + begin.length(), b).trim();
	}
}
